<template>
  <view class="container">
    <button @click="downloadImage">下载并显示图片</button>
    <image :src="imagePath" mode="aspectFit" v-if="imagePath" class="preview-image" />
    <view class="tip" v-else>点击按钮开始下载</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imagePath: '' // 存储下载后图片的临时路径
    }
  },
  methods: {
    downloadImage() {
      uni.downloadFile({
        url: 'https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg',
        // 监听下载进度
        onProgressUpdate: (res) => {
          console.log(`下载进度：${res.progress}%`);
          console.log(`已下载字节数：${res.totalBytesWritten}`);
          console.log(`总字节数：${res.totalBytesExpectedToWrite}`);
        },
        success: (res) => {
          if (res.statusCode === 200) {
            this.imagePath = res.tempFilePath; // 赋值临时路径以显示图片
            console.log('图片下载成功，临时路径：', res.tempFilePath);
          }
        },
        fail: (err) => {
          console.error('图片下载失败：', err);
          uni.showToast({
            title: '下载失败，请重试',
            icon: 'none'
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
}
.preview-image {
  width: 100%;
  max-height: 600rpx;
  margin-top: 30rpx;
}
.tip {
  margin-top: 30rpx;
  color: #999;
  font-size: 28rpx;
}
button {
  width: 280rpx;
  height: 80rpx;
  line-height: 80rpx;
}
</style>